<template>
  <div class="content">
    <el-card class="content-card">
      <div slot="header" class="row-bg-query">
        <div><el-input v-model="params.nickName" size="small" placeholder="请输入用户昵称" clearable /></div>
        <div><el-input v-model="params.email" size="small" placeholder="请输入邮箱" clearable /></div>
        <div><el-button type="primary" size="small" icon="el-icon-search" @click="search">搜索</el-button></div>
      </div>
      <div class="refresh"><el-button type="primary" size="small" icon="el-icon-refresh-left" @click="refresh">刷新</el-button></div>
      <el-table v-loading="loading" :data="users" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="180" align="center" />
        <el-table-column prop="username" label="帐号" align="center" />
        <el-table-column prop="nickName" label="昵称" width="100" align="center" />
        <el-table-column prop="avatar" label="头像" align="center">
          <template slot-scope="scope">
            <el-image :src="scope.row.avatar" :preview-src-list="[scope.row.avatar]" class="avatar" alt="scope.row.avatar" />
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" align="center" />
        <el-table-column prop="link" label="链接" width="100" align="center">
          <template slot-scope="scope">
            <el-link :href="scope.row.link" type="primary" target="_blank">博客链接</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="用户类型" width="180" align="center">
          <template slot-scope="scope">
            <el-tag :type="tagType[scope.row.type]">{{ userType[scope.row.type] }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isRegister" label="是否注册" width="80" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.isRegister === 0 ? '否' : '是' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" align="center" />
        <el-table-column align="center" label="操作" fixed="right">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog title="修改用户信息" :visible.sync="dialogFormVisible" width="30%">
      <el-form :model="form">
        <el-form-item label="昵称" label-width="20%">
          <el-input v-model="form.nickName" class="form-input" clearable />
        </el-form-item>
        <el-form-item label="头像" label-width="20%">
          <el-upload
            ref="upload"
            class="avatar-uploader"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
            :data-id="form.id || 0"
            action="https://jsonplaceholder.typicode.com/posts/"
          >
            <img v-if="form.avatar" :src="form.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="邮箱" label-width="20%">
          <el-input v-model="form.email" class="form-input" />
        </el-form-item>
        <el-form-item label="链接" label-width="20%">
          <el-input v-model="form.link" class="form-input" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" :loading="buttonLoading" @click="handleAddOrUpdate">保 存</el-button>
      </div>
    </el-dialog>
    <el-pagination
      v-if="page.pages"
      background
      layout="prev, pager, next"
      :current-page.sync="params.current"
      :page-size="page.size"
      :page-count="page.pages"
      @current-change="turnPage"
    />
  </div>
</template>

<script>
import { getList, addOrUpdate } from '@/api/user'
import { upload } from '@/api/support'

export default {
  data() {
    return {
      loading: false,
      params: {
        current: 1,
        size: 10
      },
      page: {
        current: 1,
        size: 10
      },
      userType: {
        0: '普通用户',
        1: '博主'
      },
      tagType: {
        0: 'info',
        1: 'success'
      },
      users: [],
      dialogFormVisible: false,
      buttonLoading: false,
      form: {
        nickName: null,
        avatar: null,
        email: null,
        link: null
      }
    }
  },
  watch: {
    'page.current': function(newCurrent) {
      this.params.current = newCurrent
    },
    'params.email': function(newEmail) {
      if (newEmail === '' || newEmail === null) {
        this.params.email = null
      }
    },
    'params.nickName': function(newNickName) {
      if (newNickName === '' || newNickName === null) {
        this.params.nickName = null
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    handleEdit(index, row) {
      this.dialogFormVisible = true
      if (this.form.id === null || this.form.id !== row.id) {
        this.form.id = row.id
        this.form.nickName = row.nickName
        this.form.avatar = row.avatar
        this.form.email = row.email
        this.form.link = row.link
      }
    },
    // 获取文章列表
    fetchData() {
      this.loading = true
      getList(this.params).then(response => {
        if (response.code === 200) {
          this.users = response.data.records
          this.page.current = response.data.current
          this.page.size = response.data.current
          this.page.total = response.data.total
          this.page.pages = response.data.pages
        } else {
          this.$message({
            type: 'error',
            message: response.message
          })
        }
        this.loading = false
      })
    },
    // 添加或修改标签
    handleAddOrUpdate() {
      this.buttonLoading = true
      addOrUpdate(this.form).then(response => {
        if (response.code === 200) {
          this.fetchData()
          this.$notify({
            title: '成功',
            message: '保存成功',
            type: 'success',
            duration: 2000
          })
        } else {
          this.$notify({
            title: '请求失败',
            message: response.message,
            type: 'error',
            duration: 2000
          })
        }
        this.buttonLoading = false
        this.dialogFormVisible = false
      })
    },
    // 上传成功
    handleUploadSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      this.article.image = this.imageUrl
      this.handleUpload(file)
    },
    // 上传之前判断是否是图片
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 上传文件，获取文件流
    handleUpload(file) {
      const raw = file.raw
      const formData = new FormData()
      formData.append('objectId', this.$refs.upload.$el.getAttribute('data-id'))
      formData.append('code', 1)
      formData.append('files', raw)
      upload(formData).then(response => {
        if (response.code === 200) {
          this.article.image = response.data.url
          this.$notify({
            title: '成功',
            message: '上传成功',
            type: 'success',
            duration: 2000
          })
        }
      })
    },
    // 搜索
    search() {
      this.fetchData()
    },
    // 翻页
    turnPage() {
      this.fetchData()
    },
    // 刷新
    refresh() {
      this.fetchData()
    }
  }
}
</script>

<style scoped>
  .avatar {
    width:50px;
    height:50px;
    border-radius: 50%
  }

  .form-input {
    width: 80%;
  }
</style>
